package com.samsung.eci.wiki.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.samsung.eci.wiki.bean.WikiContentVersions;
import com.samsung.eci.wiki.bean.WikiContents;
import com.samsung.eci.wiki.bean.WikiPages;
import com.samsung.eci.wiki.dao.WikiContentVersionsMapper;
import com.samsung.eci.wiki.dao.WikiContentsMapper;
import com.samsung.eci.wiki.dao.WikiPagesMapper;
import com.samsung.eci.wiki.service.WikiPagesService;

@Service
public class WikiPagesServiceImpl implements WikiPagesService {

	@Autowired
	private WikiPagesMapper wikiPagesMapper;
	@Autowired
	private WikiContentsMapper wikiContentsMapper;
	@Autowired
	private WikiContentVersionsMapper wikiContentsVerMapper;

	@Override
	@Transactional
	public int insert(WikiPages record, String content) {
		wikiPagesMapper.insert(record);
		int pageId = record.getId();
		if (pageId != 0) {
			// WikiContents contents = new WikiContents();
			WikiContents contents = null;
			List<WikiContents> conList = wikiContentsMapper
					.selectByPageId(pageId);
			// 存在更新contents表，新增到version表，不存在新增到contents表和version表
			// 反正都是要新增到version表
			// contents.setText(content);

			if (conList != null && conList.size() > 0) {
				contents = conList.get(0);
				contents.setVersion(contents.getVersion() + 1);
				contents.setText(content);
				wikiContentsMapper.updateByPrimaryKey(contents);
			} else {
				contents = new WikiContents();
				contents.setText(content);
				contents.setVersion(1);
				contents.setPageId(pageId);
				contents.setComments("");
				contents.setAuthorId(1);
				wikiContentsMapper.insert(contents);
			}
			// 新增version
			WikiContentVersions versions = new WikiContentVersions();
			versions.setAuthorId(1);
			versions.setComments("");
			versions.setCompression("");
			versions.setData(content.getBytes());
			versions.setPageId(pageId);
			versions.setVersion(contents.getVersion());
			versions.setWikiContentId(contents.getId());
			wikiContentsVerMapper.insert(versions);
		}

		return record.getId();
	}

	@Override
	public WikiPages selectByPrimaryKey(Integer id) {
		return null;
	}

	@Override
	public List<WikiPages> selectAll() {
		return null;
	}

	@Override
	public int updateByPrimaryKey(WikiPages record) {
		return 0;
	}

}
